﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Utility.Random;

namespace Utility.BehaviourTree
{
	public class RandomSelectorNode : CompositeNode
	{
		List<int> perm = new List<int> ();
		int permIndex = 0;

		protected override bool OnStart ()
		{
			if (perm.Count != childNodes.Count)
			{
				perm.Clear ();
				for (int i = 0; i < childNodes.Count; i++)
				{
					perm.Add (i);
				}
			}
			DataBoard.Shuffle (perm);
			return true;
		}

		protected override Status OnUpdate ()
		{
			BTNode curr;
			while (permIndex < childNodes.Count)
			{
				int index = perm[permIndex];
				curr = childNodes[index];
				switch (curr.Update ())
				{
					case Status.Success:
						return Status.Success;
					case Status.Failure:
						permIndex++;
						break;
					case Status.Running:
						return Status.Running;
				}
			}

			return Status.Failure;

		}

		protected override void OnReset ()
		{
			base.OnReset ();
			permIndex = 0;
		}

	}

	public class RandomSequenceNode : CompositeNode
	{
		List<int> perm = new List<int> ();
		int permIndex = 0;

		protected override bool OnStart ()
		{
			if (perm.Count != childNodes.Count)
			{
				perm.Clear ();
				for (int i = 0; i < childNodes.Count; i++)
				{
					perm.Add (i);
				}
			}
			DataBoard.Shuffle (perm);
			return true;
		}

		protected override Status OnUpdate ()
		{
			BTNode curr;
			while (permIndex < childNodes.Count)
			{
				curr = childNodes[permIndex];
				switch (curr.Update ())
				{
					case Status.Success:
						permIndex++;
						break;
					case Status.Failure:
						return Status.Failure;
					case Status.Running:
						return Status.Running;
				}
			}
			return Status.Failure;

		}

		protected override void OnReset ()
		{
			base.OnReset ();
			permIndex = 0;
		}

	}
}